import { ref, onMounted, computed } from 'vue';

export function useScrollText(text, speed) {
  const scrollPosition = ref(0);
  const scrollContainer = ref(null);

  const scrollStyle = computed(() => ({
    transform: `translateX(-${scrollPosition.value}px)`,
    transition: `transform ${speed}s linear`
  }));

  const startScrolling = () => {
    const containerWidth = scrollContainer.value.offsetWidth;
    const textWidth = scrollContainer.value.scrollWidth;

    if (textWidth > containerWidth) {
      const totalDistance = textWidth - containerWidth;
      const duration = totalDistance / speed;

      const scroll = () => {
        scrollPosition.value += 1;
        if (scrollPosition.value <= totalDistance) {
          requestAnimationFrame(scroll);
        } else {
          scrollPosition.value = 0;
          setTimeout(scroll, 1000); // 停顿1秒后重新开始
        }
      };

      scroll();
    }
  };

  onMounted(() => {
    startScrolling();
  });

  return { scrollStyle, scrollContainer };
}
